<template>
  <div id="login">
    <el-card>
      <template #header>
      <div>
        <img :src="logo" alt="">
        <span>登陆</span>
      </div>
      </template>
      <el-form label-width="55px" label-position="right">
        <el-form-item label="用户名">
          <el-input type="text" v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login()">登陆</el-button>
          <!-- router-link点击进入注册页面 -->
          <router-link to="/regist">注册</router-link>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import logo from "../assets/logo.png";
export default {
  data() {
    return {
      logo,
      form: {
        username: "",
        password: ""
      }
    };
  },
  beforeRouteEnter(to, form, next) {
    next(vm => {
      vm.isLogin(1, "/home");
    });
  },
  methods: {
    async isLogin() {
      const { data: { data } } = await this.axios({
        url: "/users/islogin"
      });
      // 已经登陆状态不能返回登陆页面
      if (data != 0) {
        this.$router.push({
          path: "/home"
        });
      }
    },
    async login() {
      const { data } = await this.axios({
        method: "post",
        url: "/users/login",
        data: {
          username: this.form.username,
          password: this.form.password
        }
      }).catch(() => {
        this.$message.error("登陆失败");
      });
      if (data) {
        this.$router.push({
          path: "/home"
        });
      }
    }
  }
};
</script>

<style lang="scss">
#login {
  width: 400px;
  margin: 0 auto;
  margin-top: 100px;
}
</style>


